package com.powernode.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.tea.TeaException;
import com.powernode.config.AliyunMessageConfig;
import com.powernode.constant.MemberConstants;
import com.powernode.domain.Member;
import com.powernode.ex.handler.BusinessException;
import com.powernode.mapper.MemberMapper;
import com.powernode.service.SendService;
import com.powernode.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.Map;

/**
 *
 */
@Service
public class SendServiceImpl implements SendService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AliyunMessageConfig aliyunMessageConfig;

    @Autowired
    private MemberMapper memberMapper;
    @Override
    public void sendPhoneMsg(Map<String, Object> map) throws Exception {
        // 获取手机号码
        String phonenum = (String) map.get("phonenum");

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，访问服务的AccessKeyId
                .setAccessKeyId(aliyunMessageConfig.getAccessKeyId())
                // 必填，访问服务的AccessKeySecret
                .setAccessKeySecret(aliyunMessageConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        // 初始化客户端
        com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
        // 创建请求参数对象
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phonenum);
        sendSmsRequest.setSignName(aliyunMessageConfig.getSignName());
        sendSmsRequest.setTemplateCode(aliyunMessageConfig.getTemplateCode());
        // 生成一个随机数字（验证码）
        String code = generatePhoneCode(4);
        // 将生成的随机数字存放到redis缓存中
        stringRedisTemplate.opsForValue().set(MemberConstants.PHONE_NUMBER_PREFIX+phonenum,code, Duration.ofMinutes(30));
        String templateParam = "{\"code\":\""+code+"\"}";
        sendSmsRequest.setTemplateParam(templateParam);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        }catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    private String generatePhoneCode(int count) {
        return RandomUtil.randomNumbers(count);
    }


    @Override
    public Boolean savePhone(Map<String, Object> map) {
        // 获取用户输入的验证码
        String code = (String) map.get("code");
        // 从redis中获取验证码
        String phonenum = (String) map.get("phonenum");
        String redisCode = stringRedisTemplate.opsForValue().get(MemberConstants.PHONE_NUMBER_PREFIX + phonenum);
        // 验证用户输入的与redis缓存中的是否一致
        if (!code.equals(redisCode)) {
            throw new BusinessException("短信验证有误，请重新输入");
        }
        // 将手机号码更新到用户信息中
        Long userId = AuthUtils.getLoginUserId();
        Member member = new Member();
        member.setId(userId);
        member.setUserMobile(phonenum);
        member.setUpdateTime(new Date());

        return memberMapper.updateById(member)>0;
    }
}
